package com.lgs7907.simplestockinfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.mywidget.xlistview.XListView;
import com.mywidget.xlistview.XListView.IXListViewListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Activity thisActivity;// 窗口上下文

	private XListView mListView;// 表格对象
	private MyListAdapter mAdapter;// 适配器

	private final static int numPerTime = 100;// 一次读完
	protected static final int MESSAGE_UPDATE_LIST = 1000;

	private StockDb mStockDb;
	private String sStockInfo;
	private Cursor mCursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 去除title
		// requestWindowFeature(Window.FEATURE_NO_TITLE);//系统顶部的菜单
		// 等效 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

		// 去掉Activity上面的状态栏
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_main);

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		findViewById(R.id.btnAdd).setOnTouchListener(mDelayHideTouchListener);
		findViewById(R.id.btnAdd).setOnClickListener(new clickListener());

		thisActivity = this;// 窗口上下文

		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(false);

		// Set up the user interaction to manually show or hide the system UI.
		mListView.setOnItemClickListener(new ItemClickListener());// 添加消息处理

		mStockDb = MyApplication.getStockDb();
		// initDatabase();

		mCursor = mStockDb.select();
	}

	@Override
	public void onResume() {
		super.onResume();

		mAdapter = new MyListAdapter();// 数据来源
		mListView.setAdapter(mAdapter);// 添加并且显示
		getNewInfo();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.itemAbout) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.itemMore:
			//Toast.makeText(getApplicationContext(), R.string.retrieves, Toast.LENGTH_SHORT).show();
			//TODO 显示更多的程序列表
			String staticServerIp = "http://119.29.74.189:8080";
			String appUrlHtml = staticServerIp+"/article_reader/app_list.html";
			Intent intent = new Intent(thisActivity, HtmlReadActivity.class); // 历史
			intent.putExtra("DATAID", 0);
			intent.putExtra("DATATITLE", "获取更多程序");
			intent.putExtra("DATAURL", appUrlHtml);
			startActivity(intent);
			break;
		case R.id.itemAbout:
			doAbout();
			break;
		}
		return false;
	}

	// 弹出关于框
	private void doAbout() {
		Dialog dialog = new AlertDialog.Builder(this).setTitle(R.string.itemAbout)
				.setMessage(R.string.about)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						// 按钮事件
					}
				}).create();
		dialog.show();
	}
	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			return false;
		}
	};

	// 表格单击处理
	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 显示所选Item的ItemView的行数
			if (position < 1)
				return;
			int pos = position - 1;
		}
	}

	class clickListener implements OnClickListener {
		public void onClick(View v) {

			if (v.getId() == R.id.btnAdd) {
				final EditText ev_code = new EditText(thisActivity);
				ev_code.setInputType(InputType.TYPE_CLASS_TEXT);
				ev_code.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });
				AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity);
				builder.setTitle("输入代码").setIcon(android.R.drawable.ic_dialog_info).setView(ev_code)
						.setNegativeButton("取消", null);
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String sCode = ev_code.getText().toString();
						// 代码都不能为空，或者退出
						if (sCode.equals("")) {
							return;
						}

						insert(sCode);
						getNewInfo();
					}
				});
				builder.show();
			}
		}
	}

	private class OnItemChildClickListener implements View.OnClickListener {
		// 点击类型索引，对应前面的enumFieldIndex
		private int itemIndex;
		// 点击列表位置
		private int position;

		public OnItemChildClickListener(int position, int itemIndex) {
			this.itemIndex = itemIndex;
			this.position = position;
		}

		public void onClick(View v) {
			if (position < 0)
				return;
			if (itemIndex == enumFieldIndex.FIELD_DELETE.ordinal()) {

				delete(position);
				mListView.invalidateViews();

				Toast.makeText(thisActivity, "Delete Successed!", Toast.LENGTH_SHORT).show();

			} else if (itemIndex == enumFieldIndex.FIELD_NAME.ordinal()) {

				Intent intent = new Intent(thisActivity, StockInfoActivity.class);
				// 历史
				intent.putExtra("POSITION", position);
				startActivity(intent);
			}
		}
	}

	private enum enumFieldIndex {
		FIELD_CODE, FIELD_NAME, FIELD_LAST_PRICE, FIELD_LAST_CHANGE, FIELD_DELETE // 界面空间不够可以省掉
	};

	public class MyListItem {
		public View itemView;
		private TextView tvCode;
		private TextView tvName;
		private TextView tvLastPrice;
		private TextView tvLastChange;

		public int position;
		private TextView tvDelete;

		public MyListItem() {

			LayoutInflater mInflater = LayoutInflater.from(thisActivity);
			itemView = mInflater.inflate(R.layout.list_item_stock, null);

			tvCode = (TextView) itemView.findViewById(R.id.list_item_code);
			tvName = (TextView) itemView.findViewById(R.id.list_item_name);
			tvLastPrice = (TextView) itemView.findViewById(R.id.list_item_last_price);
			tvLastChange = (TextView) itemView.findViewById(R.id.list_item_last_change);

			tvDelete = (TextView) itemView.findViewById(R.id.list_item_delete);
		}

		public void setPostion(int position2) {
			this.position = position2;
		}

		public void setListItem(String code, String name, Double price, Double change) {

			tvCode.setText(code);
			tvName.setText(name);
			tvName.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG|Paint.DITHER_FLAG|Paint.FAKE_BOLD_TEXT_FLAG);
			tvName.setOnClickListener(new OnItemChildClickListener(position, enumFieldIndex.FIELD_NAME.ordinal()));

			tvLastPrice.setText(String.valueOf(price));

			tvLastChange.setText(String.valueOf(change) + "%");
			if (change > 0)
				tvLastChange.setTextColor(Color.RED);
			else if (change < 0)
				tvLastChange.setTextColor(Color.rgb(0x0, 0x64, 0x0));
			else
				tvLastChange.setTextColor(Color.BLACK);

			tvDelete.setText("删除");
			tvDelete.setOnClickListener(new OnItemChildClickListener(position, enumFieldIndex.FIELD_DELETE.ordinal()));

			Drawable redDrawable = getResources().getDrawable(R.drawable.lightgray);
			itemView.setBackgroundDrawable(redDrawable);
		}
	}

	class MyListAdapter extends BaseAdapter {
		@SuppressWarnings("unchecked")
		public MyListAdapter() {
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			MyListItem ll = null;
			if (convertView != null) {
				ll = (MyListItem) convertView.getTag();
			} else {
				ll = new MyListItem();
				convertView = ll.itemView;
				convertView.setTag(ll);
			}

			SimpleInfo info = getInfo(position);
			ll.setPostion(position);// 关键点，需要一个真正的对应值
			ll.setListItem(info.code, info.stock_name, info.stock_current_price, info.stock_current_change);
			return convertView;
		}

		public int getCount() {
			return ((MainActivity) thisActivity).getCount();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}
	}

	Runnable mRefreshRunnable = new Runnable() {
		@Override
		public void run() {
			mAdapter = new MyListAdapter();// 数据来源
			mListView.setAdapter(mAdapter);// 添加并且显示
			getNewInfo();

		}
	};
	Runnable mLoadMoreRunnable = new Runnable() {
		@Override
		public void run() {
			getNewInfo();// 追加数据。
		}
	};

	class ixListListener implements IXListViewListener {
		@Override
		public void onRefresh() {
			mHandler.postDelayed(mRefreshRunnable, 300);
		}

		@Override
		public void onLoadMore() {
			mHandler.postDelayed(mLoadMoreRunnable, 300);
		}
	}

	private void refreshListView() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime("刚刚");
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// 横向
			// setContentView(R.layout.file_list_landscape);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 设置竖屏
		} else {
			// 竖向
			// setContentView(R.layout.file_list);
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback(){
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_UPDATE_LIST:
					// TODO
					// mAdapter.notifyDataSetChanged(); // 更新数据
					// refreshListView();
					mListView.invalidateViews();
					break;
			}
			return false;
		}
	});

	private void initDatabase() {
		SQLiteDatabase db = mStockDb.getReadableDatabase();
		mStockDb.onUpgrade(db, 1, 1);

		mCursor = mStockDb.select();
		mCursor.moveToFirst();
		while (!mCursor.isAfterLast()) {
			String sCode = mCursor.getString(mCursor.getColumnIndex(StockDb.STOCK_CODE));
			mStockDb.delete(sCode);
			mCursor.moveToNext();// 确认只有一条数据
		}
		// mStockDb.insert("s_sh000001");//上证指数数据结构不同
		mStockDb.insert("sh600026");
		mStockDb.insert("sh600221");
		mStockDb.insert("sh600028");
		mStockDb.insert("sh600029");
		mStockDb.insert("sh600162");
		mStockDb.insert("sh601006");
	}

	public void getAllStockInfo() {
		mStockDb.lock();
		mCursor = mStockDb.select();
		int count = mCursor.getCount();
		while (mCursor.moveToNext()) {
			String sCode = mCursor.getString(mCursor.getColumnIndex(StockDb.STOCK_CODE));
			String url = "http://hq.sinajs.cn/list=" + sCode;
			// String url = "http://hq.sinajs.cn/list=sh601006";
			sStockInfo = executeHttpGet(url);
			// Log.d(GetPostUtil.TAG, result);
			if (sStockInfo != null && sStockInfo.length() > 0) {
				mStockDb.update(sCode, sStockInfo);
				Log.e("dddd", "get info Successed!sCode=" + sCode + " url=" + url);
			}
		}
		mStockDb.unlock();
	}

	public int getCount() {
		mStockDb.lock();
		int count = (int)mStockDb.getProfilesCount();
		mStockDb.unlock();
		return count;
	}

	public void delete(int position) {
		mStockDb.lock();

		mCursor = mStockDb.select();
		mCursor.moveToPosition(position);
		String code = mCursor.getString(0);
		if (!code.equals("")) {
			mStockDb.delete(code);
		}
		mStockDb.unlock();
	}

	public void getNewInfo() {
		new Thread() {
			public void run() {
				// TODO
				getAllStockInfo();
				// handler.sendEmptyMessage(0x123);// 通知UI线程更新界面
				Message msg = mHandler.obtainMessage();
				msg.what = MESSAGE_UPDATE_LIST;
				mHandler.sendMessage(msg);

			}
		}.start();

	}

	protected void insert(String sCode) {
		mStockDb.lock();
		mStockDb.insert(sCode);
		mStockDb.unlock();
	}

	public SimpleInfo getInfo(int position) {
		mStockDb.lock();
		SimpleInfo info = new SimpleInfo();
		Cursor mCursor;
		mCursor = mStockDb.select();
		if (mCursor != null) {
			mCursor.moveToPosition(position);
			info.code = mCursor.getString(0);
			info.stock_name = mCursor.getString(1);
			info.stock_current_price = mCursor.getDouble(4);
			info.stock_current_change = mCursor.getDouble(37);
		}
		mStockDb.unlock();

		return info;
	}

	public String executeHttpGet(String sUrl) {
		// sUrl = "http://hq.sinajs.cn/list=sh601006";
		String result = "";
		URL url = null;
		HttpURLConnection connection = null;
		InputStreamReader in = null;
		try {
			url = new URL(sUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("contentType", "GBK");
			connection.setConnectTimeout(5 * 1000);
			connection.setRequestMethod("GET");

			in = new InputStreamReader(connection.getInputStream(), "GBK");
			BufferedReader bufferedReader = new BufferedReader(in);
			StringBuffer strBuffer = new StringBuffer();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				strBuffer.append(line);
			}
			result = strBuffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}
